Background: Decided to participate in a 36 hour ‘over the weekend’ data science hackathon. No aspirations of placing, just learning. What I’m presenting here is my interpretation of the question, and approach to the problem. (Unfortunately, there was some ambiguity as to the actual structure of the problem*)
Basically a two-parter. Part A You, a data scientist at an insurance company, are trying to predict the probability of policy renewal for each customer (standard ‘churn’ problem, logistic regression). Part B was the optimization, and my main focus here: You can spend extra (Incentives) to have agents pay closer attention to clients, and thereby gain an Increase in Probability of renewal. This relationship is not linear, but rather defined the figure below.
pacman::p_load(tidyverse, plotROC, pROC, DMwR2, plotly)
fun.3 <- function(x) .2*(1-exp(-2*(1-exp(-x/400))))
p <- ggplot(data=data.frame(x=0), mapping = aes(x=x))
q <- p + stat_function(fun = fun.3)+xlim(0,1500)+ylim(0,.175)+
xlab('Incentives Spent to Increase Renewal Probability')+
ylab('Increase in Prob: delta_P')
ggplotly(q)
Terms
Incentive money spent to improve Probability of RenewalPremium cost of the policyP(baseline) model’s predictions of renewal probability, before incentivesdelta_P improvement in Probability of Renewal from IncentiveP(incentivized) is the improved Probability of Renewal, after incentives, so P(baseline) + delta_PThe optimization (Part B) is to maximize the following formula for Total Net Revenue, summed across all the rows of the dataset:
( P(incentivized) * Premium ) - Incentive
Basically, you are multipling the Premium (revenue), by your odds of receiving it (renewal probability), after accounting for costs (in this case, just the incentive to boost renewal probability). This is summed across all individual clients (rows in the dataset). Real life is more complicated, the goal here is a simple optimization toy problem.
My approach: Work out the relationships between variables using function approximation.
P(baseline) to 1, because small delta_Ps don’t cost very much (curve is steepest close to origin). It’s also the majority of cases, ~94%.
delta_P*Premium - IncentiveScoring was a weighted average that favored (70% of score) the AUC for your Part A solution, with the remaining ~30% calculated from your total net revenue. I’ve included some code at the end to approximate this (solution checker page taken down after competition, boo)
A simple logistic regression on untransformed variables performed fairly well in this case. (predictor variables included: age, number of premiums paid on time/late, income, and underwriter/credit score).
The classifier isn’t the focus here, so I’ll just show the quick and dirty code for Part A. The DMwR2 package in R makes kNN imputation quite easy - as there were a handful of NAs in both the training and test sets.
train <- read.csv('train.csv')
trainCC <- knnImputation(train[,-c(1)])
lr0 <- glm(renewal ~ ., data = trainCC, family = 'binomial')
lr0pred <- predict(lr0, trainCC, type = 'resp')
trainCC$lr0pred <- lr0pred
ggplot(trainCC, aes(d=renewal, m = lr0pred))+geom_roc()
roc <- roc(trainCC$renewal, lr0pred); auc<-roc$auc; auc # on training
## Area under the curve: 0.8317
Sometime soon I’ll make a companion post exploring how to optimize the binary classifier model. But since the best AUC I saw was ~0.85, I call that darn good for a first-pass. FWIW, feature engineering/transforms did little to enhance the model, according to several of the top-ranked participants, and my own fiddling (quite frustrating!).
The first step was to figure out the optimum ‘ROI’ for Incentives, across the range of policy premiums. The smart way is to plot the equation, where z = ROI, x = Incentives, and y = Premium. It gives you a 3d surface - find the equation that defines the maximum for each x,y and you’re all set.
fun.3d <- function(x,y) (.2*(1-exp(-2*(1-exp(-x/400))))*y) - x
Except I don’t have the math skills to make that happen. The plot sure is pretty though…
incentives <- seq(0,1000,10)
premium <- seq(1200,60000, length.out=101)
roi <- as.matrix(read.csv('surface.csv', header = F))
plot_ly(x=~incentives,
y=~premium,
z=~roi) %>% add_surface()
Instead I turned to (old faithful) Excel, and plotted a poor man’s 3d surface. We already know the relationship between Incentive and Increase in Probability delta_P, so we can multiply the latter by a range of premium amounts, and deduct the incentives paid to calculate the ROI (see below). Then you can use conditional formatting to easily spot the top 3 values per column.
The highlighted table in yellow is a list of values we can now fit to get a good approximation of that relationship. The output of that fit will tell us the optimal Incentive for each value of Premium. Note: ideal incentive maxes out at ~920, for the 60k upper limit on the range of policy Premiums in our dataset. Because of the asymptotic shape of that curve, it makes sense there is an upper limit, and that corresponds to an Percent Increase delta_P of 0.1669.
ideal <- read.csv('ideal.csv', header=T) # from excel
colnames(ideal) <- c('premium', 'incentive')
tail(ideal)
## premium incentive
## 10 20000 580
## 11 25000 650
## 12 30000 700
## 13 40000 790
## 14 50000 860
## 15 60000 920
range(ideal$incentive)
## [1] 20 920
ggplot(ideal, aes(x=premium, y=incentive))+geom_point()
Now, this part will not make sense to most people - but since my background is in Pharmacology, I thought “gee that looks an awful lot like a sigmoidal dose response relationship.” So, I download the drc package to fit the data. I guess you’ll just have to trust me that it makes sense (and I’m sure there are other packages and formulas that would approximate the fit just fine).
library(drc); library(modelr)
drc <- drm(incentive ~ premium, data = ideal, fct = LL.4(), type = 'continuous')
rsquare(drc, ideal)
## [1] 0.9997965
plot(drc, log = '', cex = 2)
Looks pretty close. Now we can call predict() to get the optimal Incentive as a function of Premium!
Now.. What about people who are already very likely to renew their policy? We used Excel and curve fitting to calculate the ideal maximum amount to spend on Incentive, as a function of Premium - above which our ROI starts to decline. But people with a low Probability of Renewal P(baseline) are a relatively small portion of the dataset (~6%). Performing well overall will require optimizing ROI from the majority who are already near P(baseline)=1.
Also noted from the Excel sheet: spending less than the optimal amount never resulted in a negative ROI. In other words, it is always worth spending a little to bump up your P(baseline) to 1, even if it was already very high.
Therefore, the first step on the test set is to calculate how much ‘room’ for improvement there is before you hit P(renewal) = 1. That is simply 1 - P(baseline) – which again is just the output of our logistic regression model.
test <- read.csv('test.csv') #read in
testCC <- knnImputation(test[,-c(1)]) # don't use id for knn
testCC <- cbind(id = test$id, testCC) # add it back
testPred <- predict(lr0, testCC, type = 'response') # get P(baseline) for test set
testCC$pred <- testPred # add back to dataframe
testCC$room <- 1 - testCC$pred # calculate room for improvement
OK, next is where we run into a problem: We have a new maximum for how much we should incentivize, but in units of Y (based on the relationship we already have for those variables; see fun.3 above).
AND, the equation is ridiculously complicated, to the point that Wolfram Alpha can’t even solve for X. We could go back to school for a math degree, OR… use another function approximation from observable data points.
y = seq(0,1000, 10) # range of incentives, new Y
deltaP <- fun.3(y) # Increase Prob for range of incentives, new X
solveX <- data.frame(x=deltaP, y=y)
solveX <- solveX[2:101,] # get rid of origin, zeros
tail(solveX)
## x y
## 96 0.1673989 950
## 97 0.1675483 960
## 98 0.1676933 970
## 99 0.1678342 980
## 100 0.1679709 990
## 101 0.1681038 1000
plot((solveX$x), log(solveX$y))
Wild. Ok, looks like a 3rd order polynomial might be able to approximate.
model <- lm(log(y) ~ x + I(x^2) + I(x^3) -1, data=solveX) # -1 = no intercept term, force thru origin
summary(model)
##
## Call:
## lm(formula = log(y) ~ x + I(x^2) + I(x^3) - 1, data = solveX)
##
## Residuals:
## Min 1Q Median 3Q Max
## -0.26135 -0.03762 -0.01638 0.06507 1.11193
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## x 134.896 2.901 46.50 <2e-16 ***
## I(x^2) -1213.932 45.699 -26.56 <2e-16 ***
## I(x^3) 3904.845 176.162 22.17 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.1812 on 97 degrees of freedom
## Multiple R-squared: 0.9991, Adjusted R-squared: 0.9991
## F-statistic: 3.666e+04 on 3 and 97 DF, p-value: < 2.2e-16
Well, I’m satisfied with the R-squared. Now we have a way to go from the ‘room’ variable (room for improvement before you hit probability of 1) to Incentive.
model$coefficients
## x I(x^2) I(x^3)
## 134.8965 -1213.9316 3904.8455
fun.model <- function(x) exp( (model$coefficients[1]*x )+
(model$coefficients[2]*(x^2))+
(model$coefficients[3]*(x^3)) )
We’ll use this to calculate what the incentive should be, when the ‘room’ for improvement is less than what the ideal incentive (only a function of premium) would suggest.
Here is the code to finish these calculations on the test set to get our predictions. If you followed along so far, this should be no problem.
testX <- testCC[,c(1,12:14)] # dplyr 'select' knitr fail
testX <- testX %>%
mutate(delta_P = pmin(room, 0.1669)) %>%
mutate(p_incentives = pred + delta_P) %>%
mutate(ideal_incentive = predict(drc, testCC[c('id','premium')])) %>% # optimum based on premium
mutate(room_incentive = fun.model(delta_P)) %>% # max spend dictated by headroom
mutate(incentives = trunc(pmin(ideal_incentive, room_incentive))) %>% # take the lower value
mutate(new_prob = fun.3(incentives) + pred) # sanity check
head(testX, 10)
## id premium pred room delta_P p_incentives
## 1 649 3300 0.9898966 0.01010340 0.01010340 1.0000000
## 2 81136 11700 0.9787123 0.02128767 0.02128767 1.0000000
## 3 70762 11700 0.9186891 0.08131092 0.08131092 1.0000000
## 4 53935 5400 0.9701324 0.02986761 0.02986761 1.0000000
## 5 15476 9600 0.9571893 0.04281073 0.04281073 1.0000000
## 6 64797 11700 0.9776386 0.02236144 0.02236144 1.0000000
## 7 67412 3300 0.5922917 0.40770834 0.16690000 0.7591917
## 8 44241 5400 0.8720873 0.12791273 0.12791273 1.0000000
## 9 5069 13800 0.9847190 0.01528100 0.01528100 1.0000000
## 10 16615 28500 0.9881246 0.01187544 0.01187544 1.0000000
## ideal_incentive room_incentive incentives new_prob
## 1 180.2902 3.466078 3 0.9928632
## 2 447.2463 10.582377 10 0.9883485
## 3 447.2463 154.759570 154 1.0131355
## 4 273.4742 21.118711 21 0.9895791
## 5 399.5626 47.302057 47 0.9969612
## 6 447.2463 11.624723 11 0.9881996
## 7 180.2902 947.130939 180 0.6954019
## 8 273.4742 261.216012 261 0.9953949
## 9 488.7091 6.000377 6 0.9905864
## 10 687.9440 4.209308 4 0.9920653
So, the caveat is that because my function approximations weren’t perfect, if I calculate the percentage of improvement based on what I spent, I have some instances where it seems like I’m spending more than I should.
over1 <- testX %>%
filter(new_prob >= 1) %>% # uh oh?
arrange(desc(new_prob))
head(over1, 10)
## id premium pred room delta_P p_incentives
## 1 73714 26400 0.9243101 0.07568995 0.07568995 1
## 2 97179 13800 0.9250901 0.07490988 0.07490988 1
## 3 68806 7500 0.9239201 0.07607991 0.07607991 1
## 4 103903 7500 0.9235314 0.07646865 0.07646865 1
## 5 17160 22200 0.9242994 0.07570062 0.07570062 1
## 6 2374 5400 0.9235211 0.07647888 0.07647888 1
## 7 6956 5400 0.9239052 0.07609477 0.07609477 1
## 8 42637 18000 0.9254659 0.07453412 0.07453412 1
## 9 45410 7500 0.9254658 0.07453423 0.07453423 1
## 10 32156 5700 0.9239029 0.07609708 0.07609708 1
## ideal_incentive room_incentive incentives new_prob
## 1 665.6823 141.0298 141 1.013903
## 2 488.7091 139.0090 139 1.013902
## 3 343.1634 142.0297 142 1.013900
## 4 343.1634 143.0195 143 1.013896
## 5 616.3146 141.0572 141 1.013892
## 6 273.4742 143.0455 143 1.013885
## 7 273.4742 142.0676 142 1.013885
## 8 558.5628 138.0259 138 1.013884
## 9 343.1634 138.0262 138 1.013884
## 10 284.5246 142.0735 142 1.013883
There is no mechanism in place to detect or penalize for that (aside from lost revenue), so you could leave them as-is, or scale down the incentives by a certain percentage (seems to happen mostly when the premium is within a certain range). I’ll leave it to you to play with.
nrow(over1) / nrow(testCC)
## [1] 0.18937
summary(over1$incentives)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 1.0 86.0 126.0 128.3 167.0 692.0
Of me: I got distracted as the deadline approached, and never submitted for a final score. I had made submissions that were on the top ~1/3 of the leaderboard before figuring out the optimization part.
Of the platform it’s a dud for people coming to learn:
A bit anti-climactic I suppose. Lesson learned: Stick to Kaggle if you’re learning.
If you have some optimization experience or math chops, I’d love to know the ‘right’ way to go about this problem, so if you have an opinion or alternate strategy, even a link to a useful tutorial, please share!
Here is some code to approximate your score on the test set (which is pretty easy to do, if you just use AUC on the training data)
# revenue without incentives, wi
# 0.9 threshold for renewal
wi <- sum(
(ifelse(testX$pred>=.9,testX$pred,0) )*testX$premium) # 317M
# total possible revenue; sum of premiums
all <- sum(testX$premium) # 370M
# your revenue after incentives
rev <- sum((testX$p_incentives*testX$premium)-testX$incentives) # 364M
incent_score <- (rev-wi)/(all-wi); incent_score
## [1] 0.883308
score = (.7 * auc) + .3*(incent_score); score
## [1] 0.8471608
Just a quick way to check your own ideas re: optimization. You would do a test-train split if you wanted to have a better idea of out-of-bag performance of your binary classifier.